﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DeployGames.TweenEngine.TestBed.core
{
    public class FPSCounter
    {
        private const int BUFFER_SIZE = 25;
        private long[] myTicks = new long[BUFFER_SIZE];
        private int myIdx;

        private decimal myFPS;
        public decimal FPS
        {
            get
            {
                return myFPS;
            }
        }

        private long myRefreshRate;
        public long RefreshRate
        {
            get
            {
                return myRefreshRate;
            }
            set
            {
                myRefreshRate = value;
            }
        }

        private long myFreq;

        public long Frequency
        {
            get { return myFreq; }
            set { myFreq = value; }
        }

        private long myTick;
        public void tick(long tick)
        {
            myTicks[myIdx++] = tick;
            if (myIdx >= BUFFER_SIZE)
                myIdx = 0;

            myTick += tick;
            if (myTick > myRefreshRate)
            {
                myTick = 0;
                myFPS = count();
            }
        }

        private decimal count()
        {
            long sum = 0;
            foreach (long i in myTicks)
                sum += i;

            if (sum == 0)
                return 0;

            return myFreq / (sum / myTicks.Length);
        }

        public override string ToString()
        {
            return String.Format("FPS: {0}", FPS);
        }
    }
}
